package top.jacktgq.cas.aba;
/**
 * 
 * @Title: ABADemo2.java 
 * @Package top.jacktgq.nolock.aba 
 * @Description: AtomicMarkableReference的用法
 * @author CandyWall   
 * @date 2020年11月2日 下午10:01:24 
 * @version V1.0
 */

import java.util.concurrent.atomic.AtomicMarkableReference;

import top.jacktgq.utils.LogUtils;
import top.jacktgq.utils.Sleeper;

public class ABA_AtomicMarkedReference2 {
	public static void main(String[] args) {
		LogUtils.log("ABA_AtomicMarkedReference2", "main start...");
		GarbageBag garbageBag = new GarbageBag("装满了垃圾");
		//参数2 mark 可以看做一个标记，表示垃圾袋满了
		AtomicMarkableReference<GarbageBag> ref 
					= new AtomicMarkableReference<GarbageBag>(garbageBag, true);
		GarbageBag prev = ref.getReference();
		LogUtils.log("ABA_AtomicMarkedReference2", prev.toString());
		
		new Thread(() -> {
			LogUtils.log("ABA_AtomicMarkedReference2", "start...");
			garbageBag.setDesc("空垃圾袋");
			boolean success = ref.compareAndSet(garbageBag, garbageBag, true, false);
			LogUtils.log("ABA_AtomicMarkedReference2", "换了吗？" + success);
		}, "保洁阿姨").start();;
		
		Sleeper.sleep(1);
		
		LogUtils.log("ABA_AtomicMarkedReference2", "想换一只新垃圾袋吗？");
		boolean success = ref.compareAndSet(prev, new GarbageBag("空垃圾袋"), true, false);
		LogUtils.log("ABA_AtomicMarkedReference2", "换了吗？ " + success);
		LogUtils.log("ABA_AtomicMarkedReference2", ref.getReference().toString());
		
	}
}

//垃圾袋
class GarbageBag {
	String desc;

	public GarbageBag(String desc) {
		this.desc = desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	@Override
	public String toString() {
		return "GarbageBag [desc=" + desc + "]";
	}
	
}
